package com.xinghai.web.controller.api;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.xinghai.common.core.domain.AjaxResult;
import com.xinghai.common.core.redis.RedisCache;
import com.xinghai.common.utils.PageUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.common.utils.WeChatUtil;
import com.xinghai.common.utils.http.HttpUtils;
import com.xinghai.system.domain.*;
import com.xinghai.system.domain.vo.UrlsVo;
import com.xinghai.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/")
public class ApiController {

    @Autowired
    private IJsBannerService jsBannerService;
    @Autowired
    private IJsClassificationService jsClassificationService;
    @Autowired
    private IJsGoodService jsGoodService;
    @Autowired
    private IJsBrandService jsBrandService;
    @Autowired
    private IJsBankService jsBankService;
    @Autowired
    private IJsQuestionService jsQuestionService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IJsActivityService activityService;
    @Autowired
    private IJsStepService stepService;

    @PostMapping("/common/banners")
    public AjaxResult banners(JsBanner jsBanner)
    {
        jsBanner.setStatus("0");
        List<JsBanner> list = jsBannerService.list(jsBanner);
        return new AjaxResult(1, "success", list);
    }

    @PostMapping("/common/activity")
    public AjaxResult banners(String activity_id)
    {
        JsActivity o = activityService.getInfo(Long.valueOf(activity_id));
        Map<String, Object> map = new HashMap<>();
        if (o==null){
            map.put("id", "0");
            map.put("content", "活动已结束");
            map.put("images", new ArrayList<>());
            map.put("imange", "");
            map.put("name", "活动已结束");
            map.put("views", "0");
            map.put("desc", "");
        }else {
            map.put("id", o.getId());
            map.put("content", o.getContent());
            map.put("images", o.getImage());
            map.put("imange", o.getImage());
            map.put("name", o.getName());
            map.put("views", o.getViews());
            map.put("desc", o.getDesc());
        }
        return new AjaxResult(1, "success", map);
    }

    @PostMapping("/common/activities")
    public AjaxResult activities(JsActivity activity)
    {
        PageUtils.startPage(activity.getPage(), 10);
        activity.setStatus("0");
        List<JsActivity> list = activityService.list(activity);
        long total = new PageInfo(list).getTotal();
        List<Map<String, Object>> collect = list.stream().map(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", o.getId());
            map.put("content", o.getContent());
            map.put("images", o.getImage());
            map.put("imange", o.getImage());
            map.put("name", o.getName());
            map.put("views", o.getViews());
            map.put("desc", o.getDesc());
            return map;
        }).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("current_page", activity.getPage());
        map.put("last_page", total / 10 + 1);
        map.put("per_page", 10);
        map.put("total", total);
        map.put("data", collect);
        return new AjaxResult(1, "success", map);
    }


    @PostMapping("/common/question")
    public AjaxResult question(String question_id)
    {
        JsQuestion jsQuestion = jsQuestionService.getInfo(Long.valueOf(question_id));
        Map<String, Object> map = new HashMap<>();
        map.put("id", jsQuestion.getId());
        map.put("title", jsQuestion.getQuestion());
        map.put("content", jsQuestion.getContent());
        map.put("views", jsQuestion.getReadCount());
        return new AjaxResult(1, "success", map);
    }



    @PostMapping("/gift/questions")
    public AjaxResult giftQuestions()
    {
        JsQuestion jsQuestion = new JsQuestion();
        jsQuestion.setStatus("0");
        jsQuestion.setType("1");
        List<JsQuestion> list = jsQuestionService.list(jsQuestion);
        List<Map<String, Object>> collect = list.stream().map(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", o.getId());
            map.put("title", o.getQuestion());
            map.put("content", o.getContent());
            return map;
        }).collect(Collectors.toList());
        return new AjaxResult(1, "success", collect);
    }

    @PostMapping("/gift/info")
    public AjaxResult giftInfo(String gift_id)
    {
        JsGood jsGood = jsGoodService.getInfo(Long.valueOf(gift_id));
        Map<String, Object> map = new HashMap<>();
        map.put("id", jsGood.getId());
        map.put("title", jsGood.getName());
        map.put("contents", jsGood.getContent());
        map.put("bank_nums", jsGood.getNeedCardNum());
        map.put("bank_ids", jsGood.getBankId());
        String remark = jsGood.getRemark();
        if (StringUtils.isNotBlank(remark)){
            remark = "("+remark+")";
        }
        map.put("bank_name", jsGood.getBankName()+remark);
        map.put("image", jsGood.getImgUrl());
        map.put("stocks", jsGood.getStockStatus());
        List<JsBank> jsBanks = jsBankService.listByIds(jsGood.getBankId());
        map.put("banks", jsBanks.stream().peek(o -> o.setStatus("1")));
        return new AjaxResult(1, "success", map);
    }
    @PostMapping("/gift/rules")
    public AjaxResult rules()
    {
        JsStep jsStep = new JsStep();
        jsStep.setStatus("0");
        List<JsStep> list = stepService.list(jsStep);
        List<Map<String, Object>> collect = list.stream().map(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", o.getId());
            map.put("steps", o.getSteps());
            map.put("note", o.getName());
            map.put("status", o.getStatus());
            map.put("sort", o.getSort());
            return map;
        }).collect(Collectors.toList());
        return new AjaxResult(1, "success", collect);
    }


    @PostMapping("/gift/list")
    public AjaxResult list(JsGood jsGood) {
        PageUtils.startPage(jsGood.getPage(), 10);
        if (jsGood.getBank_id()!=0){
            jsGood.setBankId(String.valueOf(jsGood.getBank_id()));
        }
        if (jsGood.getBank_nums()!=0){
            jsGood.setNeedCardNum(jsGood.getBank_nums());
        }
        if (jsGood.getBrand_id()!=0){
            jsGood.setBrandId(String.valueOf(jsGood.getBank_id()));
        }
        if (jsGood.getCid()!=0){
            jsGood.setClassification(String.valueOf(jsGood.getCid()));
        }
        if (StringUtils.isNotBlank(jsGood.getKeywords())){
            jsGood.setName(jsGood.getKeywords());
        }
        jsGood.setStatus("0");
        List<JsGood> list = jsGoodService.list(jsGood);
        long total = new PageInfo(list).getTotal();
        List<Map<String, Object>> collect = list.stream().map(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", o.getId());
            map.put("title", o.getName());
            map.put("image", o.getImgUrl());
            map.put("bank_nums", o.getNeedCardNum());
            map.put("bank_name", o.getBankName());
            map.put("bank_ids", o.getBankId());
            return map;
        }).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("current_page", jsGood.getPage());
        map.put("last_page", total / 10 + 1);
        map.put("per_page", 10);
        map.put("total", total);
        map.put("data", collect);
        return new AjaxResult(1, "success", map);
    }

    @PostMapping("/common/questions")
    public AjaxResult questions(JsQuestion jsQuestion)
    {
        PageUtils.startPage(jsQuestion.getPage(),10);
        jsQuestion.setStatus("0");
        List<JsQuestion> list = jsQuestionService.list(jsQuestion);
        long total = new PageInfo(list).getTotal();
        List<Map<String, Object>> collect = list.stream().map(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", o.getId());
            map.put("title", o.getQuestion());
            map.put("view", o.getReadCount());
            map.put("content", o.getContent());
            return map;
        }).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("current_page", jsQuestion.getPage());
        map.put("last_page", total/10+1);
        map.put("per_page", 10);
        map.put("total", total);
        map.put("data", collect);
        return new AjaxResult(1, "常见问题列表", map);
    }

    @PostMapping("/common/steps")
    public AjaxResult steps()
    {
        JsQuestion jsQuestion = new JsQuestion();
        jsQuestion.setQuestion("礼品领取流程");
        List<JsQuestion> list = jsQuestionService.list(jsQuestion);
        if (list.isEmpty()){
            return new AjaxResult(1, "领取流程", "");
        }
        return new AjaxResult(1, "领取流程", list.get(0));
    }

    @PostMapping("/category/indexTop")
    public AjaxResult indexTop()
    {
        JsClassification jsClassification = new JsClassification();
        jsClassification.setStatus("0");
        jsClassification.setFirstShow("0");
        List<JsClassification> list = jsClassificationService.list(jsClassification);
        List<Map<String, Object>> collect1 = list.stream().map(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", o.getId());
            map.put("name", o.getName());
            map.put("image", o.getImgUrl());
            return map;
        }).collect(Collectors.toList());
        return new AjaxResult(1, "分类集合", collect1);
    }

    @PostMapping("/gift/bank")
    public AjaxResult giftBank(JsBank jsBank)
    {
        JsBank bank = jsBankService.getInfo(jsBank.getBank_id());
        Map<String, Object> map = new HashMap<>();
        map.put("contents", bank.getContent());
        map.put("image", bank.getImage());
        map.put("logo", bank.getLogo());
        map.put("name", bank.getName());
        map.put("id", bank.getId());
        map.put("bank_url", "");
        map.put("code_url", "");
        return new AjaxResult(1, "信用卡详情", map);
    }
    @PostMapping("/category/list")
    public AjaxResult categoryList()
    {
        JsClassification jsClassification = new JsClassification();
        jsClassification.setStatus("0");
        List<JsClassification> list1 = jsClassificationService.list(jsClassification);
        List<Map<String, Object>> collect1 = list1.stream().map(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", o.getId());
            map.put("name", o.getName());
            map.put("image", o.getImgUrl());
            return map;
        }).collect(Collectors.toList());
        JsBrand jsBrand = new JsBrand();
        jsBrand.setStatus("0");
        List<JsBrand> list2 = jsBrandService.list(jsBrand);
        List<Map<String, Object>> collect2 = list2.stream().map(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", o.getId());
            map.put("name", o.getName());
            map.put("image", o.getImgUrl());
            return map;
        }).collect(Collectors.toList());
        JsBank jsBank = new JsBank();
        jsBank.setStatus("0");
        jsBank.setpId(0L);
        List<JsBank> list3 = jsBankService.list(jsBank);
//        List<Map<String, Object>> collect3 = list3.stream().map(o -> {
//            Map<String, Object> map = new HashMap<>();
//            map.put("id", o.getId());
//            map.put("title", o.getName());
//            return map;
//        }).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> bankNums = getMaps();
        map.put("bank_nums", bankNums);
        map.put("categories", collect1);
        map.put("brands", collect2);
        map.put("banks", list3);
        return new AjaxResult(1, "分类集合", map);
    }

    private static List<Map<String, Object>> getMaps() {
        List<Map<String, Object>> bankNums = new ArrayList<>();
        Map<String, Object> bank1 = new HashMap<>();
        bank1.put("bank_name", "1卡");
        bank1.put("bank_nums", "1");
        bankNums.add(bank1);
        Map<String, Object> bank2 = new HashMap<>();
        bank2.put("bank_name", "2卡");
        bank2.put("bank_nums", "2");
        bankNums.add(bank2);
        Map<String, Object> bank3 = new HashMap<>();
        bank3.put("bank_name", "3卡");
        bank3.put("bank_nums", "3");
        bankNums.add(bank3);
        Map<String, Object> bank4 = new HashMap<>();
        bank4.put("bank_name", "4卡");
        bank4.put("bank_nums", "4");
        bankNums.add(bank4);
        Map<String, Object> bank5 = new HashMap<>();
        bank5.put("bank_name", "4卡以上");
        bank5.put("bank_nums", "5");
        bankNums.add(bank5);
        return bankNums;
    }

    public static void main(String[] args) {
//        JSONArray array = new JSONArray();
//        for (int i = 1; i <= 53; i++){
//            String s = HttpUtils.sendPost("https://asbk.56yidi.com/v1/gift/list", "page="+i);
//            JSONObject jsonObject = JSONObject.parseObject(s);
//            JSONArray parse = JSONArray.parse(JSONObject.parseObject(jsonObject.getString("data")).getString("data"));
//            array.addAll(parse);
//        }
//        JSONArray array1 = new JSONArray();
//        for (Object object:array){
//            JSONObject from = JSONObject.from(object);
//            String s = HttpUtils.sendPost("https://asbk.56yidi.com/v1/gift/info", "gift_id="+from.getString("id"));
//            JSONObject jsonObject = JSONObject.parseObject(JSONObject.parseObject(s).getString("data"));
//            Iterator<String> keys = jsonObject.keySet().iterator();
//            while (keys.hasNext()) {
//                String key = keys.next();
//                Object value = jsonObject.get(key);
//                from.put(key, value);
//            }
//            array1.add(from);
//        }
//        System.out.println(JSONObject.toJSONString(array1));
//        JSONArray array3 = new JSONArray();
//        for (int i = 1; i <= 2; i++){
//            String s = HttpUtils.sendPost("https://asbk.56yidi.com/v1/common/questions", "page="+i);
//            JSONObject jsonObject = JSONObject.parseObject(s);
//            JSONArray parse = JSONArray.parse(JSONObject.parseObject(jsonObject.getString("data")).getString("data"));
//            array3.addAll(parse);
//        }
//        List<JSONObject> collect1 = array3.stream().map(o -> {
//            JSONObject from = JSONObject.from(o);
//            String s = HttpUtils.sendPost("https://asbk.56yidi.com/v1/common/question", "question_id=" + from.get("id"));
//            JSONObject data = JSONObject.parseObject(JSONObject.parseObject(s).getString("data"));
//            from.put("small_content", from.getString("content"));
//            from.put("content", data.getString("content"));
//            return from;
//        }).collect(Collectors.toList());
//        System.out.println("____________________________问题数据start____________________________");
//        System.out.println(JSONObject.toJSONString(collect1));
//        System.out.println("____________________________问题数据end____________________________");
        String s = HttpUtils.sendPost("https://asbk.56yidi.com/v1/category/list", "");
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
        JSONArray parse1 = JSONArray.parse(data.getString("brands"));
        System.out.println("____________________________品牌数据start____________________________");
        System.out.println(JSONObject.toJSONString(parse1));
        System.out.println("____________________________品牌数据end____________________________");
        System.out.println("____________________________分类数据start____________________________");
        JSONArray parse2 = JSONArray.parse(data.getString("categories"));
        System.out.println(JSONObject.toJSONString(parse2));
        String s0 = HttpUtils.sendPost("https://asbk.56yidi.com/v1/category/indexTop", "");
        JSONObject jsonObject0 = JSONObject.parseObject(s0);
        JSONArray parse0 = JSONArray.parse(jsonObject0.getString("data"));
        Map<Object, Object> id = parse0.stream().collect(Collectors.toMap(o -> JSONObject.from(o).get("id"), o -> o));
        List<JSONObject> collect = parse2.stream().map(o -> {
            JSONObject from = JSONObject.from(o);
            if (id.get(from.get("id")) != null) {
                from.put("first_show", "0");
            }
            return from;
        }).collect(Collectors.toList());
        System.out.println("____________________________处理首页显示数据____________________________");
        System.out.println(JSONObject.toJSONString(collect));
        System.out.println("____________________________分类数据end____________________________");
//        String s1 = HttpUtils.sendPost("https://asbk.56yidi.com/v1/common/banners", "");
//        JSONObject jsonObject1 = JSONObject.parseObject(s1);
//        JSONArray parse4 = JSONArray.parse(jsonObject1.getString("data"));
//        System.out.println("____________________________轮播图数据start____________________________");
//        System.out.println(JSONObject.toJSONString(parse4));
//        System.out.println("____________________________轮播图数据end____________________________");
//        String s2 = HttpUtils.sendPost("https://asbk.56yidi.com/v1/gift/rules", "");
//        JSONObject jsonObject2 = JSONObject.parseObject(s2);
//        JSONArray parse5 = JSONArray.parse(jsonObject2.getString("data"));
//        System.out.println("____________________________兑换说明数据start____________________________");
//        System.out.println(JSONObject.toJSONString(parse5));
//        System.out.println("____________________________兑换说明数据end____________________________");
        Map<String, Object> mapGood = new HashMap<>();
        for (Object object:parse1){
            JSONObject from = JSONObject.from(object);
            String s3 = HttpUtils.sendPost("https://asbk.56yidi.com/v1/gift/list", "brand_id="+from.get("id")+"&page=1");
            JSONObject jsonObject3 = JSONObject.parseObject(JSONObject.parseObject(s3).getString("data"));
            JSONArray parse3 = JSONArray.parse(jsonObject3.getString("data"));
            int lastPage = Integer.parseInt(jsonObject3.getString("last_page"));
            for (int i = 2; i <= lastPage; i++) {
                String s4 = HttpUtils.sendPost("https://asbk.56yidi.com/v1/gift/list", "brand_id="+from.get("id")+"&page="+i);
                JSONObject jsonObject4 = JSONObject.parseObject(JSONObject.parseObject(s4).getString("data"));
                JSONArray parse6 = JSONArray.parse(jsonObject4.getString("data"));
                parse3.addAll(parse6);
            }
            parse3.forEach(o -> {
                JSONObject from1 = JSONObject.from(o);
                if (!mapGood.containsKey(from1.getString("id"))){
                    mapGood.put(from1.getString("id"),from.get("id"));
                }else {
                    mapGood.put(from1.getString("id"),mapGood.get(from1.getString("id"))+","+from.get("id"));
                }
            });
        }
        System.out.println("____________________________根据品牌查询商品start____________________________");
        mapGood.keySet().forEach(key->{
            System.out.println("update js_good set brand_id = "+mapGood.get(key)+" where id = "+key+";");
        });
        System.out.println("____________________________根据品牌查询商品end____________________________");
        Map<String, Object> mapCe = new HashMap<>();
        for (Object object:parse1){
            JSONObject from = JSONObject.from(object);
            String s3 = HttpUtils.sendPost("https://asbk.56yidi.com/v1/gift/list", "cid="+from.get("id")+"&page=1");
            JSONObject jsonObject3 = JSONObject.parseObject(JSONObject.parseObject(s3).getString("data"));
            JSONArray parse3 = JSONArray.parse(jsonObject3.getString("data"));
            int lastPage = Integer.parseInt(jsonObject3.getString("last_page"));
            for (int i = 2; i <= lastPage; i++) {
                String s4 = HttpUtils.sendPost("https://asbk.56yidi.com/v1/gift/list", "cid="+from.get("id")+"&page="+i);
                JSONObject jsonObject4 = JSONObject.parseObject(JSONObject.parseObject(s4).getString("data"));
                JSONArray parse6 = JSONArray.parse(jsonObject4.getString("data"));
                parse3.addAll(parse6);
            }
            parse3.forEach(o -> {
                JSONObject from1 = JSONObject.from(o);
                if (!mapCe.containsKey(from1.getString("id"))){
                    mapCe.put(from1.getString("id"),from.get("id"));
                }else {
                    mapCe.put(from1.getString("id"),mapCe.get(from1.getString("id"))+","+from.get("id"));
                }
            });
        }
        System.out.println("____________________________根据分类查询商品start____________________________");
        System.out.println(JSONObject.toJSONString(mapCe));
        mapCe.keySet().forEach(key->{
            System.out.println("update js_good set classification = "+mapCe.get(key)+" where id = "+key+";");
        });
        System.out.println("____________________________根据分类查询商品end____________________________");
    }
    /**
     * 获取微信加密信息
     * @return
     */
    @PostMapping(value = "/wxjs/getSignature")
    public AjaxResult toTranscript(@RequestParam("urls") String urls) {
        System.out.println(urls);
        Map<String, Object> wxInfo = new HashMap<>();
        try {
            // 获取accessToken
            String accessToken =redisCache.getCacheObject("accessToken");

             //判断accessToken是否过期
            if (StringUtils.isNull(accessToken)){
                accessToken = WeChatUtil.getAccessToken();
                redisCache.setCacheObject("accessToken",accessToken,110, TimeUnit.MINUTES);
            }

            //获取jsapiTicket
            String jsapiTicket =redisCache.getCacheObject("jsapiTicket");

            //判断jsapiTicket是否过期
            if (StringUtils.isNull(jsapiTicket)){
                jsapiTicket = WeChatUtil.getTicket(accessToken);
                redisCache.setCacheObject("jsapiTicket",jsapiTicket,110, TimeUnit.MINUTES);
            }

            String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
            String timestamp = String.valueOf(System.currentTimeMillis()/ 1000);// 时间戳
            String params = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url="+urls;

            //将字符串进行sha1加密
            String signature = WeChatUtil.getSHA1(params);
            //微信appId
            String appId = WeChatUtil.appIdWx;
            wxInfo.put("appId", appId);
            wxInfo.put("nonceStr", noncestr);
            wxInfo.put("share_content","办卡免费兑好礼，遛娃神器、宠物智能投喂器、小家电、露营装备、安全座椅、母婴礼品等，所有商品均从天猫、京东等大平台下单，包售后");
            wxInfo.put("share_img", "https://jsh5.wffdwl.top/logo/logo.png");
            wxInfo.put("share_title", "锦颂礼品部落");
            wxInfo.put("signature", signature);
            wxInfo.put("timestamp", timestamp);
            return new AjaxResult(1, "签名结果", wxInfo);
        } catch (Exception e) {
            wxInfo.put("code", "0");
            wxInfo.put("status", "0");
            wxInfo.put("msg", "error");
            return AjaxResult.error();
        }
    }
}
